package net.zjitc.utils;

import io.jsonwebtoken.*;
import lombok.Data;
import net.zjitc.service.ManagerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @author 毛钰深
 * @create 2022/1/23
 */
@Data
@Component
//从配置文件中注入,前缀为shop.jwt
@ConfigurationProperties(prefix = "shop.jwt")
public class JwtUtils {

    //自定义的过期时间(天)
    private long time;

    //自定义的加密秘钥
    private String secret;

    //放入响应头的key名,一般都是Authorization
    private String header;

    @Autowired
    private ManagerService managerService;

    //生成jwt
    public String generateToken(String username){

        Date nowDate = new Date();
        Date expireDate= new Date(nowDate.getTime()+ 1000*60*60*24*time);

        return Jwts.builder()
                .setHeaderParam("alg","HS256")
                .setHeaderParam("typ","JWT")
                .setSubject(username)
                .setIssuedAt(nowDate)
                .setExpiration(expireDate)  //一天过期
                .signWith(SignatureAlgorithm.HS256,secret)
                .compact();
    }

    //解析jwt  不合法->null
    public Claims getClaimByToken(String jwt){
        try {
            return Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(jwt)
                    .getBody();
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * jwt是否过期
     * @param claims
     * @return
     * true -> 过期
     * false->没过期
     */
    public boolean isTokenExpired(Claims claims){
        return claims.getExpiration().before(new Date());
    }

}
